package act.ein3c.in3;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.Buffer;
import java.util.ArrayList;

public class Receiver implements Runnable {
	private int requestNumber = 0;
	private ServerSocket ss;
	private DataOutputStream outToOther;
	private ArrayList<String> received;

	public static void main(String[] args){
		Receiver r = new Receiver();		
		r.run();
	}
	
	
	public Receiver() {
		requestNumber = 0;
		received = new ArrayList<String>();

		try {
			ss = new ServerSocket(9090);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	public void run(){
			boolean running = true;
			
			try {
				Socket senderSocket = ss.accept();
				String type = "";
				
				//TODO
				InputStream i = senderSocket.getInputStream();
		
				ObjectInputStream oi = new ObjectInputStream(i);
				while(running){
					Object o = oi.readObject();
					outToOther = new DataOutputStream(senderSocket.getOutputStream());
					Packet packet;
					if(o instanceof Packet){
						
						packet = (Packet) o;
						System.out.println("Receiver: is packet number " + packet.getNumber());
						System.out.println("Receiver: requestNumber " + requestNumber);
						if(packet.getNumber() == requestNumber && packet.getInputData() != null ){					
							//accept packet
							System.out.println("Receiver: accept packet");
							

							sendAck();
							
							String inhoud = packet.getInputData();
							received.add(inhoud);
							
							System.out.println("Receiver: ontvangen " + inhoud);
							
							requestNumber++;
						}else{
							System.err.println("Receiver: Verkeerde packetnr");
							type = "w";
							outToOther.writeBytes(new String(type +" " + (requestNumber) )+'\n');
						
						}
					} else{
						//error
						System.err.println("Receiver: Error Receiver ln 77");
					}
				}
				
			} catch (IOException e) {
				System.err.println("Receiver: Geen Connectie, dus close");
				System.out.println("Receiver: Ontvangen berichten");
				for(String message : received){
					System.out.println("Receiver: Message: "+ message + " ontvangen");
				}
				try {
					ss.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			} catch (ClassNotFoundException e) {
				
				e.printStackTrace();
			}
			

			
		
	}

	private void sendAck() throws IOException {
		String type;
		type = "a";
		outToOther.writeBytes(new String(type + " " + requestNumber) + '\n');
	}
}
